<template>
  <div class="snack-management">
    <div class="header">
      <h2>零食管理</h2>
      <div class="header-buttons">
        <el-button type="primary" @click="showCategoryDialog">分类管理</el-button>
        <el-button type="primary" @click="showAddDialog">新增零食</el-button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-bar">
      <el-input
        v-model="searchQuery"
        placeholder="搜索零食名称"
        style="width: 200px"
        clearable
        @input="handleSearch"
      />
      <el-select
        v-model="categoryFilter"
        placeholder="分类筛选"
        clearable
        @change="handleSearch"
      >
        <el-option
          v-for="category in categoryList"
          :key="category.id"
          :label="category.name"
          :value="category.id"
        />
      </el-select>
    </div>

    <!-- 零食列表 -->
    <el-table :data="filteredSnacks" style="width: 100%" v-loading="loading">
      <el-table-column prop="name" label="名称" />
      <el-table-column prop="price" label="售价">
        <template #default="scope">
          ¥{{ scope.row.price }}
        </template>
      </el-table-column>
      <el-table-column prop="stock" label="库存">
        <template #default="scope">
          {{ scope.row.stock }}{{ scope.row.unit }}
          <el-tag 
            :type="scope.row.stock < 10 ? 'danger' : 'success'"
            size="small"
          >
            {{ scope.row.stock < 10 ? '库存不足' : '库存充足' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="category_name" label="分类">
        <template #default="scope">
          {{ scope.row.category_name }}
        </template>
      </el-table-column>
      <el-table-column prop="is_active" label="状态">
        <template #default="scope">
          <el-tag :type="scope.row.is_active ? 'success' : 'info'">
            {{ scope.row.is_active ? '在售' : '下架' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="280">
        <template #default="scope">
          <el-button-group>
            <el-button size="small" @click="showEditDialog(scope.row)">
              编辑
            </el-button>
            <el-button 
              size="small" 
              type="primary"
              @click="showStockDialog(scope.row)"
            >
              调整库存
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogType === 'add' ? '新增零食' : '编辑零食'"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form 
        :model="form" 
        :rules="rules" 
        ref="snackForm" 
        label-width="100px"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="售价" prop="price">
          <el-input-number 
            v-model="form.price" 
            :min="0" 
            :precision="2" 
          />
        </el-form-item>
        <el-form-item label="成本价" prop="cost">
          <el-input-number 
            v-model="form.cost" 
            :min="0" 
            :precision="2" 
          />
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input-number 
            v-model="form.stock" 
            :min="0" 
            :precision="0" 
          />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="form.unit" />
        </el-form-item>
        <el-form-item label="分类" prop="category_id">
          <el-select v-model="form.category_id">
            <el-option
              v-for="category in categoryList"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="描述">
          <el-input 
            v-model="form.description" 
            type="textarea" 
            :rows="2"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="form.is_active"
            :active-value="true"
            :inactive-value="false"
            active-text="在售"
            inactive-text="下架"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 库存调整对话框 -->
    <el-dialog
      title="调整库存"
      v-model="stockDialogVisible"
      width="400px"
    >
      <el-form label-width="100px">
        <el-form-item label="当前库存">
          {{ currentSnack?.stock }}{{ currentSnack?.unit }}
        </el-form-item>
        <el-form-item label="调整数量">
          <el-input-number 
            v-model="stockAdjustment"
            :min="-currentSnack?.stock"
            placeholder="正数增加/负数减少"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="stockDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleStockAdjust">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分类管理对话框 -->
    <el-dialog
      title="分类管理"
      v-model="categoryDialogVisible"
      width="500px"
    >
      <div class="category-header">
        <el-input
          v-model="newCategory"
          placeholder="输入新分类名称"
          style="width: 200px"
        />
        <el-button type="primary" @click="handleAddCategory">添加分类</el-button>
      </div>
      
      <el-table :data="categoryList" style="width: 100%; margin-top: 20px;">
        <el-table-column prop="name" label="分类名称" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button-group>
              <el-button 
                size="small" 
                @click="showEditCategoryDialog(scope.row)"
              >
                编辑
              </el-button>
              <el-button 
                size="small" 
                type="danger" 
                @click="handleDeleteCategory(scope.row)"
              >
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 编辑分类对话框 -->
    <el-dialog
      title="编辑分类"
      v-model="editCategoryDialogVisible"
      width="400px"
    >
      <el-form>
        <el-form-item label="分类名称">
          <el-input v-model="editingCategory.name" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editCategoryDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleUpdateCategory">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { snackAPI } from '../api/services'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'SnackManagement',
  setup() {
    const snacks = ref([])  // 确保初始化为空数组
    const loading = ref(false)
    const dialogVisible = ref(false)
    const stockDialogVisible = ref(false)
    const dialogType = ref('add')
    const snackForm = ref(null)
    const currentId = ref(null)
    const searchQuery = ref('')
    const categoryFilter = ref('')
    const stockAdjustment = ref(0)
    const currentSnack = ref(null)
    const categoryDialogVisible = ref(false)
    const editCategoryDialogVisible = ref(false)
    const newCategory = ref('')
    const categoryList = ref([])
    const editingCategory = ref({ id: null, name: '' })

    const form = ref({
      name: '',
      price: 0,
      cost: 0,
      stock: 0,
      unit: '',
      category_id: null,
      description: '',
      is_active: true
    })

    const rules = {
      name: [
        { required: true, message: '请输入零食名称', trigger: 'blur' },
        { min: 2, message: '名称长度至少为2个字符', trigger: 'blur' }
      ],
      price: [
        { required: true, message: '请输入售价', trigger: 'blur' }
      ],
      cost: [
        { required: true, message: '请输入成本价', trigger: 'blur' }
      ],
      stock: [
        { required: true, message: '请输入库存数量', trigger: 'blur' }
      ],
      unit: [
        { required: true, message: '请输入单位', trigger: 'blur' }
      ],
      category_id: [
        { required: true, message: '请选择分类', trigger: 'change' }
      ]
    }

    const categories = computed(() => {
      return categoryList.value.map(category => category.name)
    })

    const filteredSnacks = computed(() => {
      if (!Array.isArray(snacks.value)) return []
      return snacks.value.filter(snack => {
        const matchesSearch = searchQuery.value ? 
          snack.name.toLowerCase().includes(searchQuery.value.toLowerCase()) : 
          true
        const matchesCategory = categoryFilter.value ? 
          snack.category_id === categoryFilter.value : 
          true
        return matchesSearch && matchesCategory
      })
    })

    const fetchSnacks = async () => {
      loading.value = true
      try {
        const response = await snackAPI.getSnacks()
        console.log('Snacks response:', response)
        snacks.value = response || []  // 确保 snacks.value 始终是数组
      } catch (error) {
        console.error('Failed to fetch snacks:', error)
        console.error('Error details:', error.response || error)
        ElMessage.error('获取零食信息失败')
        snacks.value = []  // 错误时设置为空数组
      } finally {
        loading.value = false
      }
    }

    const fetchCategories = async () => {
      try {
        const response = await snackAPI.getCategories()
        categoryList.value = response || []
      } catch (error) {
        console.error('Failed to fetch categories:', error)
        ElMessage.error('获取分类列表失败')
      }
    }

    const resetForm = () => {
      form.value = {
        name: '',
        price: 0,
        cost: 0,
        stock: 0,
        unit: '',
        category_id: null,
        description: '',
        is_active: true
      }
      if (snackForm.value) {
        snackForm.value.resetFields()
      }
    }

    const showAddDialog = () => {
      dialogType.value = 'add'
      resetForm()
      dialogVisible.value = true
    }

    const showEditDialog = (row) => {
      dialogType.value = 'edit'
      currentId.value = row.id
      form.value = { 
        ...row,
        category_id: row.category_id
      }
      dialogVisible.value = true
    }

    const showStockDialog = (row) => {
      currentSnack.value = row
      stockAdjustment.value = 0
      stockDialogVisible.value = true
    }

    const handleSubmit = async () => {
      if (!snackForm.value) return

      try {
        await snackForm.value.validate()
        if (dialogType.value === 'add') {
          const response = await snackAPI.createSnack(form.value)
          if (response.message === '创建成功') {
            ElMessage.success('创建成功')
          }
        } else {
          await snackAPI.updateSnack(currentId.value, form.value)
          ElMessage.success('更新成功')
        }

        dialogVisible.value = false
        await fetchSnacks()
      } catch (error) {
        console.error('Failed to submit snack:', error)
        ElMessage.error(error.response?.data?.detail || '操作失败')
      }
    }

    const handleStockAdjust = async () => {
      try {
        await snackAPI.adjustStock(currentSnack.value.id, stockAdjustment.value)
        ElMessage.success('库存调整成功')
        stockDialogVisible.value = false
        await fetchSnacks()
      } catch (error) {
        ElMessage.error(error.response?.data?.detail || '库存调整失败')
      }
    }

    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm('确定要删除该零食吗？', '提示', {
          type: 'warning'
        })
        
        await snackAPI.deleteSnack(row.id)
        
        ElMessage.success('删除成功')
        await fetchSnacks()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }

    const handleSearch = () => {
      // 搜索逻辑已通过计算属性实现
    }

    const showCategoryDialog = () => {
      categoryDialogVisible.value = true
      newCategory.value = ''
    }

    const showEditCategoryDialog = (category) => {
      editingCategory.value = { ...category }
      editCategoryDialogVisible.value = true
    }

    const handleAddCategory = async () => {
      if (!newCategory.value.trim()) {
        ElMessage.warning('请输入分类名称')
        return
      }

      try {
        await snackAPI.createCategory({ name: newCategory.value.trim() })
        ElMessage.success('添加分类成功')
        newCategory.value = ''
        await fetchCategories()
      } catch (error) {
        ElMessage.error(error.response?.data?.detail || '添加分类失败')
      }
    }

    const handleUpdateCategory = async () => {
      if (!editingCategory.value.name.trim()) {
        ElMessage.warning('请输入分类名称')
        return
      }

      try {
        await snackAPI.updateCategory(
          editingCategory.value.id,
          { name: editingCategory.value.name.trim() }
        )
        ElMessage.success('更新分类成功')
        editCategoryDialogVisible.value = false
        await fetchCategories()
      } catch (error) {
        ElMessage.error(error.response?.data?.detail || '更新分类失败')
      }
    }

    const handleDeleteCategory = async (category) => {
      try {
        await ElMessageBox.confirm(
          '删除分类可能会影响相关零食的分类，是否继续？',
          '警告',
          {
            type: 'warning',
            confirmButtonText: '确定',
            cancelButtonText: '取消'
          }
        )
        
        await snackAPI.deleteCategory(category.id)
        ElMessage.success('删除分类成功')
        await fetchCategories()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error(error.response?.data?.detail || '删除分类失败')
        }
      }
    }

    onMounted(async () => {
      await Promise.all([fetchSnacks(), fetchCategories()])
    })

    return {
      snacks,
      loading,
      dialogVisible,
      stockDialogVisible,
      dialogType,
      form,
      rules,
      snackForm,
      searchQuery,
      categoryFilter,
      categories,
      filteredSnacks,
      stockAdjustment,
      currentSnack,
      showAddDialog,
      showEditDialog,
      showStockDialog,
      handleSubmit,
      handleStockAdjust,
      handleDelete,
      handleSearch,
      categoryDialogVisible,
      editCategoryDialogVisible,
      newCategory,
      categoryList,
      editingCategory,
      showCategoryDialog,
      showEditCategoryDialog,
      handleAddCategory,
      handleUpdateCategory,
      handleDeleteCategory,
    }
  }
}
</script>

<style scoped>
.snack-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
}

.header-buttons {
  display: flex;
  gap: 10px;
}

.search-bar {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.category-header {
  display: flex;
  gap: 10px;
}
</style> 